#define  _CRT_SECURE_NO_WARNINGS
class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());
        vector<vector<int>> ret;
        if (nums.size() < 4)return ret;
        for (int i1 = 0; i1 < nums.size() - 3; i1++)
        {
            while (i1 && i1 < nums.size() - 3 && nums[i1] == nums[i1 - 1])i1++;
            for (int i2 = i1 + 1; i2 < nums.size() - 2; i2++)
            {
                while (i2 != i1 + 1 && i2 < nums.size() - 2 && nums[i2] == nums[i2 - 1])i2++;
                long long tgt = (long long)target - nums[i1] - nums[i2];
                int left = i2 + 1, right = nums.size() - 1;
                while (left < right)
                {
                    int sum = nums[left] + nums[right];
                    if (sum < tgt)left++;
                    else if (sum > tgt)right--;
                    else
                    {
                        ret.push_back({ nums[i1],nums[i2],nums[left++],nums[right--] });
                        while (left < right && nums[left] == nums[left - 1])left++;
                        while (left < right && nums[right] == nums[right + 1])right--;
                    }
                }
            }
        }
        return ret;
    }
};